﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ERPWinFormWork.Test.Test.Dtos;
using ERPWinFormWork.Test.Test.Dtos.Write;
using ERPWinFormWork.Test.TestCode;
using Newtonsoft.Json;

namespace ERPWinFormWork.Test
{
    public partial class UpdateProcurement_Pricing : Form
    {
        private string _pricingNode;
        private int? _pricingId;
        private ApiClient _apiClient;
        private Action _refreshCallback; // 添加刷新回调

        public UpdateProcurement_Pricing()
        {
            InitializeComponent();
            _apiClient = new ApiClient(TestAPI.TestApiBaseUrl);
        }

        public UpdateProcurement_Pricing(string pricingNode, Action refreshCallback = null)
        {
            InitializeComponent();
            _pricingNode = pricingNode;
            _apiClient = new ApiClient(TestAPI.TestApiBaseUrl);
            _refreshCallback = refreshCallback; // 保存刷新回调


            BindGridEvents();
            BindGlobalTaxRateEvents();
            InitializeGridAndEvents();
            // 加载页面数据（顺序很重要：先下拉，再反填）
            this.Load += async (s, e) =>
            {
                await LoadSuppliersAsync();
                await LoadPricingHeaderAsync();
                await LoadPricingMaterialsAsync();
            };
        }

        // 新增：支持按Id打开
        public UpdateProcurement_Pricing(int id, Action refreshCallback = null)
        {
            InitializeComponent();
            _pricingId = id;
            _apiClient = new ApiClient(TestAPI.TestApiBaseUrl);
            _refreshCallback = refreshCallback; // 保存刷新回调


            BindGridEvents();
            BindGlobalTaxRateEvents();
            InitializeGridAndEvents();

            this.Load += async (s, e) =>
            {
                await LoadSuppliersAsync();
                // 先通过ID获取采购核价编号，然后使用编号进行后续查询
                await LoadPricingHeaderByIdAsync();
            };
        }

        /// <summary>
        /// 初始化表格与事件
        /// </summary>
        private void InitializeGridAndEvents()
        {
            ConfigureMaterialGrid();

            if (dgvmater != null)
            {
                dgvmater.DataBindingComplete += async (s, e) =>
                {
                    var grid = dgvmater;
                    int colCount = grid.Columns.Count;
                    // 严格将三列放到最后三位（从后往前设置，避免相互影响）
                    int last = colCount - 1;
                    if (grid.Columns.Contains("colTaxedPrice")) grid.Columns["colTaxedPrice"].DisplayIndex = last--;
                    if (grid.Columns.Contains("colUntaxedPrice")) grid.Columns["colUntaxedPrice"].DisplayIndex = last--;
                    if (grid.Columns.Contains("colTaxRate")) grid.Columns["colTaxRate"].DisplayIndex = Math.Max(0, last);

                    // 数据绑定完成后，处理物料数据（设置税率、行配色等）
                    ProcessMaterialDataAfterBinding();

                    // 数据绑定完成后，加载新价格数据并反填
                    await LoadNewPricesAndFillBack();
                };
            }
        }


        /// <summary>
        /// 供应商下拉框
        /// </summary>
        /// <returns></returns>
        private async Task LoadSuppliersAsync()
        {
            try
            {
                var resp = await _apiClient.GetAsync<TestCode.TestApiResult<List<Supplier_TableDtos>>>(
                    endpoint: "api/Read/GetSupplier_Table");
                if (resp != null && resp.code == 200)
                {
                    cbosupplierId.DisplayMember = "supplierName";
                    cbosupplierId.ValueMember = "id";
                    cbosupplierId.DataSource = resp.data;
                    cbosupplierId.SelectedItem = null;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载供应商数据失败：{ex.Message}");
            }
        }



        private void BindGridEvents()
        {
            if (dgvmater != null)
            {
                dgvmater.AllowUserToAddRows = false;
                dgvmater.DataBindingComplete += (s, e) =>
                {
                    if (dgvmater.Columns.Contains("colDelete"))
                    {
                        dgvmater.Columns["colDelete"].DisplayIndex = dgvmater.Columns.Count - 1;
                    }
                };

                // 与新增页一致：根据编辑改变动态计算
                dgvmater.CellValueChanged += Dgvmater_CellValueChanged;
            }
        }

        private void BindGlobalTaxRateEvents()
        {
            if (texttax_Rate != null)
            {
                texttax_Rate.TextChanged += (s, e) =>
                {
                    UpdateAllMaterialTaxRates();
                };
            }
        }

        private async Task LoadPricingHeaderAsync()
        {
            try
            {
                var parameters = new Dictionary<string, string> { { "pricingNode", _pricingNode } };
                var resp = await _apiClient.GetAsync<TestApiResult<List<GetProcurement_PricingDtos>>>(
                    "api/Read/GetProcurementByPricingNode", parameters);
                if (resp != null && resp.code == 200 && resp.data != null && resp.data.Count > 0)
                {
                    var header = resp.data.First();
                    // 反填头信息（参考详情页）
                    if (textpricingNode != null) textpricingNode.Text = header.PricingNode ?? string.Empty;
                    if (textpricingName != null) textpricingName.Text = header.PricingName ?? string.Empty;
                    if (datepricing_Date != null) datepricing_Date.text = header.Pricing_Date.ToString("yyyy-MM-dd");

                    // 选择供应商（先尝试按Id，再退回按名称匹配）
                    TrySelectSupplier(header);

                    if (texttax_Rate != null) texttax_Rate.Text = header.Tax_Rate.ToString();
                    if (textnotes != null) textnotes.Text = header.Notes ?? string.Empty;
                }
                else
                {
                    MessageBox.Show($"获取核价头信息失败：{resp?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载核价头信息异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async Task LoadPricingHeaderByIdAsync()
        {
            if (!_pricingId.HasValue) return;
            try
            {
                var parameters = new Dictionary<string, string> { { "id", _pricingId.Value.ToString() } };
                var resp = await _apiClient.GetAsync<TestApiResult<List<GetProcurement_PricingDtos>>>(
                    "api/Read/GetProcurementById", parameters);
                if (resp != null && resp.code == 200 && resp.data != null && resp.data.Count > 0)
                {
                    var header = resp.data.First();

                    // 设置采购核价编号
                    _pricingNode = header.PricingNode;

                    if (textpricingNode != null) textpricingNode.Text = header.PricingNode ?? string.Empty;
                    if (textpricingName != null) textpricingName.Text = header.PricingName ?? string.Empty;
                    if (datepricing_Date != null) datepricing_Date.text = header.Pricing_Date.ToString("yyyy-MM-dd");
                    TrySelectSupplier(header);
                    if (texttax_Rate != null) texttax_Rate.Text = header.Tax_Rate.ToString();
                    if (textnotes != null) textnotes.Text = header.Notes ?? string.Empty;

                    // 获取到采购核价编号后，加载物料数据
                    if (!string.IsNullOrEmpty(_pricingNode))
                    {
                        await LoadPricingMaterialsAsync();
                    }
                }
                else
                {
                    MessageBox.Show($"按Id加载核价头信息失败：{resp?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"按Id加载核价头信息异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async Task LoadPricingMaterialsAsync()
        {
            try
            {
                var parameters = new Dictionary<string, string> { { "pricingNode", _pricingNode } };
                var resp = await _apiClient.GetAsync<TestApiResult<List<Material_TableDtos>>>(
                    "api/Read/FindMaterialByProcurementNode", parameters);
                if (resp != null && resp.code == 200 && resp.data != null)
                {
                    // 绑定数据
                    var list = new BindingList<Material_TableDtos>(resp.data);
                    dgvmater.DataSource = list;
                }
                else
                {
                    MessageBox.Show($"获取核价物料失败：{resp?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载核价物料异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }



        private void TrySelectSupplier(GetProcurement_PricingDtos header)
        {
            if (cbosupplierId == null) return;
            try
            {
                var supplierIdProp = header.GetType().GetProperty("SupplierId");
                if (supplierIdProp != null)
                {
                    var sid = supplierIdProp.GetValue(header);
                    if (sid != null)
                    {
                        cbosupplierId.SelectedValue = Convert.ToInt32(sid);
                        return;
                    }
                }

                // 回退按名称
                if (!string.IsNullOrWhiteSpace(header.SupplierName))
                {
                    cbosupplierId.Text = header.SupplierName;
                }
            }
            catch { }
        }

        /// <summary>
        /// 在数据绑定完成后处理物料数据（设置税率、行配色等）
        /// </summary>
        private void ProcessMaterialDataAfterBinding()
        {
            if (dgvmater == null || dgvmater.Rows.Count == 0) return;

            // 设置税率列值及行配色
            if (dgvmater.Columns.Contains("colTaxRate"))
            {
                // 获取全局税率
                int? taxRate = null;
                if (int.TryParse(texttax_Rate?.Text, out var tr) && tr >= 0) taxRate = tr;

                foreach (DataGridViewRow row in dgvmater.Rows)
                {
                    if (row.DataBoundItem is Material_TableDtos material)
                    {
                        // 税率：使用全局税率
                        row.Cells["colTaxRate"].Value = taxRate.HasValue ? (object)taxRate.Value : null;

                        // 行配色：13%税率的行使用特殊背景色
                        if (taxRate.HasValue && taxRate.Value == 13)
                        {
                            row.DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 240);
                        }

                        // 设置Tag用于后续操作
                        row.Tag = material;
                    }
                }
            }
        }

        private int GetGlobalTaxRate()
        {
            if (texttax_Rate != null && !string.IsNullOrWhiteSpace(texttax_Rate.Text) && int.TryParse(texttax_Rate.Text, out var rate))
            {
                return rate;
            }
            return 0;
        }

        private int GetTaxRate(int rowIndex)
        {
            if (dgvmater == null || rowIndex < 0 || rowIndex >= dgvmater.Rows.Count) return 0;
            var val = dgvmater.Rows[rowIndex].Cells["colTaxRate"].Value?.ToString();
            if (int.TryParse(val, out var rate)) return rate;
            return 0;
        }

        /// <summary>
        /// 加载新价格数据并反填到表格（参考ProcurementPricingDetail.cs的逻辑）
        /// </summary>
        private async Task LoadNewPricesAndFillBack()
        {
            try
            {
                Console.WriteLine("=== 开始加载新价格数据并反填 ===");
                Console.WriteLine($"采购核价编号: {_pricingNode}");
                Console.WriteLine($"表格行数: {dgvmater?.Rows.Count ?? 0}");

                if (string.IsNullOrEmpty(_pricingNode) || dgvmater == null)
                {
                    Console.WriteLine("采购核价编号为空或表格为空，退出");
                    return;
                }

                // 根据采购核价编号查询新价格数据（API返回的是数组）
                var endpoint = $"api/Read/FindPriceByProcurementNode?pricingNode={_pricingNode}";
                Console.WriteLine($"调用API: {endpoint}");

                var priceResponse = await _apiClient.GetAsync<TestApiResult<List<GetProcurement_PricingDtos>>>(
                    endpoint: endpoint,
                    parameters: null
                );

                if (priceResponse != null && priceResponse.code == 200 && priceResponse.data != null)
                {
                    var priceDataList = priceResponse.data;
                    

                    int updatedCount = 0;
                    int notFoundCount = 0;

                    // 遍历表格中的物料行，根据物料Id匹配并反填新价格
                    foreach (DataGridViewRow row in dgvmater.Rows)
                    {
                        if (row.DataBoundItem is Material_TableDtos material)
                        {
                            Console.WriteLine($"处理物料: {material.MaterialName} (ID: {material.Id})");

                            // 在价格数据列表中查找匹配的物料
                            var matchingPriceData = priceDataList.FirstOrDefault(p => p.Material_Id == material.Id);

                            if (matchingPriceData != null)
                            {
                                // 反填新未税价格到对应的列
                                if (dgvmater.Columns.Contains("colUntaxedPrice"))
                                {
                                    var untaxedValue = matchingPriceData.Untaxed_Price > 0 ? matchingPriceData.Untaxed_Price.ToString("F2") : string.Empty;
                                    row.Cells["colUntaxedPrice"].Value = untaxedValue;
                                    Console.WriteLine($"  设置新未税价格: {untaxedValue}");
                                }

                                // 反填新含税价格到对应的列
                                if (dgvmater.Columns.Contains("colTaxedPrice"))
                                {
                                    var taxedValue = matchingPriceData.Taxed_Price > 0 ? matchingPriceData.Taxed_Price.ToString("F2") : string.Empty;
                                    row.Cells["colTaxedPrice"].Value = taxedValue;
                                    Console.WriteLine($"  设置新含税价格: {taxedValue}");
                                }

                                
                                updatedCount++;
                            }
                            else
                            {
                                // 如果没有找到新价格数据，使用原价格作为默认值
                                if (dgvmater.Columns.Contains("colUntaxedPrice"))
                                {
                                    var originalUntaxed = material.OidUntaxedPrice ?? 0m;
                                    row.Cells["colUntaxedPrice"].Value = originalUntaxed > 0 ? originalUntaxed.ToString("F2") : string.Empty;
                                }

                                if (dgvmater.Columns.Contains("colTaxedPrice"))
                                {
                                    var originalTaxed = material.OidIncludingTax ?? 0m;
                                    row.Cells["colTaxedPrice"].Value = originalTaxed > 0 ? originalTaxed.ToString("F2") : string.Empty;
                                }

                               
                                notFoundCount++;
                            }
                        }
                    }

                   
                }
                else
                {
                    
                    // 如果API调用失败，使用原价格作为默认值
                    SetOriginalPricesAsDefault();
                }
            }
            catch (Exception ex)
            {

                // 异常情况下，使用原价格作为默认值
                SetOriginalPricesAsDefault();
            }
        }

        /// <summary>
        /// 设置原价格作为默认值
        /// </summary>
        private void SetOriginalPricesAsDefault()
        {
            if (dgvmater == null || dgvmater.Rows.Count == 0) return;

            Console.WriteLine("使用原价格作为默认值");
            foreach (DataGridViewRow row in dgvmater.Rows)
            {
                if (row.DataBoundItem is Material_TableDtos material)
                {
                    if (dgvmater.Columns.Contains("colUntaxedPrice"))
                    {
                        var originalUntaxed = material.OidUntaxedPrice ?? 0m;
                        row.Cells["colUntaxedPrice"].Value = originalUntaxed > 0 ? originalUntaxed.ToString("F2") : string.Empty;
                    }

                    if (dgvmater.Columns.Contains("colTaxedPrice"))
                    {
                        var originalTaxed = material.OidIncludingTax ?? 0m;
                        row.Cells["colTaxedPrice"].Value = originalTaxed > 0 ? originalTaxed.ToString("F2") : string.Empty;
                    }
                }
            }
        }


        /// <summary>
        /// 配置物料表格样式与列
        /// </summary>
        private void ConfigureMaterialGrid()
        {
            if (dgvmater == null) return;
            var grid = dgvmater;
            grid.AllowUserToAddRows = false;

            if (!grid.Columns.Contains("colTaxRate"))
            {
                var colTaxRate = new DataGridViewTextBoxColumn
                {
                    Name = "colTaxRate",
                    HeaderText = "税率%",
                    ValueType = typeof(int),
                    Width = 70,
                    ReadOnly = true
                };
                colTaxRate.DefaultCellStyle.Format = "N0";
                colTaxRate.DefaultCellStyle.NullValue = string.Empty;
                grid.Columns.Add(colTaxRate);
            }


            // 新未税价格列
            if (!grid.Columns.Contains("colUntaxedPrice"))
            {
                var colUntaxed = new DataGridViewTextBoxColumn
                {
                    Name = "colUntaxedPrice",
                    HeaderText = "新未税价格",
                    ValueType = typeof(decimal),
                    Width = 100,
                    ReadOnly = false
                };
                colUntaxed.DefaultCellStyle.Format = "N2";
                colUntaxed.DefaultCellStyle.NullValue = string.Empty;
                grid.Columns.Add(colUntaxed);
            }

            // 新含税价格列
            if (!grid.Columns.Contains("colTaxedPrice"))
            {
                var colTaxed = new DataGridViewTextBoxColumn
                {
                    Name = "colTaxedPrice",
                    HeaderText = "新含税价格",
                    ValueType = typeof(decimal),
                    Width = 100,
                    ReadOnly = false
                };
                colTaxed.DefaultCellStyle.Format = "N2";
                colTaxed.DefaultCellStyle.NullValue = string.Empty;
                grid.Columns.Add(colTaxed);
            }

            grid.EnableHeadersVisualStyles = false;
            grid.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(83, 196, 242);
            grid.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
            grid.ColumnHeadersDefaultCellStyle.Font = new Font("微软雅黑", 9F, FontStyle.Bold);
            grid.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(245, 245, 245);
        }


        private void UpdateAllMaterialTaxRates()
        {
            if (dgvmater == null || dgvmater.Rows.Count == 0) return;
            int taxRate = GetGlobalTaxRate();

            foreach (DataGridViewRow row in dgvmater.Rows)
            {
                // 设置税率列
                if (dgvmater.Columns.Contains("colTaxRate")) row.Cells["colTaxRate"].Value = taxRate.ToString();
            }

            // 税率变化后，重新加载新价格数据并反填
            _ = LoadNewPricesAndFillBack();
        }

        private void Dgvmater_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
            var grid = sender as DataGridView;
            if (grid == null) return;

            var columnName = grid.Columns[e.ColumnIndex].Name;
            if (columnName == "colTaxRate")
            {
                // 税率变化时，重新加载新价格数据并反填
                _ = LoadNewPricesAndFillBack();
            }
            else if (columnName == "colUntaxedPrice")
            {
                // 新未税价格变化时，根据税率计算新含税价格
                if (decimal.TryParse(grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value?.ToString(), out var untaxed))
                {
                    int rate = GetTaxRate(e.RowIndex);
                    var taxed = rate > 0 ? Math.Round(untaxed * (1 + rate / 100.0m), 2) : untaxed;
                    grid.Rows[e.RowIndex].Cells["colTaxedPrice"].Value = taxed.ToString("F2");
                }
            }
            else if (columnName == "colTaxedPrice")
            {
                // 新含税价格变化时，根据税率计算新未税价格
                if (decimal.TryParse(grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value?.ToString(), out var taxed))
                {
                    int rate = GetTaxRate(e.RowIndex);
                    var untaxed = rate > 0 ? Math.Round(taxed / (1 + rate / 100.0m), 2) : taxed;
                    grid.Rows[e.RowIndex].Cells["colUntaxedPrice"].Value = untaxed.ToString("F2");
                }
            }
        }



        private void btnStepwiseAdd_Click(object sender, EventArgs e)
        {
            // 直接复用新增页的按供应商选择物料逻辑
            int? supplierId = null;
            if (cbosupplierId?.SelectedValue != null && int.TryParse(cbosupplierId.SelectedValue.ToString(), out var sv))
            {
                supplierId = sv;
            }
            if (!supplierId.HasValue)
            {
                MessageBox.Show("请先选择供应商", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var dialog = new SupplierMaterial_Table(supplierId.Value, selected =>
            {
                if (selected == null) return;
                foreach (DataGridViewRow r in dgvmater.Rows)
                {
                    if (r.Cells["colMaterialNumber"].Value?.ToString() == selected.MaterialNumber)
                    {
                        MessageBox.Show("该物料已存在", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                }

                int rowIndex = dgvmater.Rows.Add();
                var row = dgvmater.Rows[rowIndex];
                row.Cells["colMaterialNumber"].Value = selected.MaterialNumber;
                row.Cells["colMaterialName"].Value = selected.MaterialName;
                row.Cells["colSpecifications"].Value = selected.Specifications;
                row.Cells["colUnitName"].Value = selected.UnitName;
                row.Cells["colOriginalUntaxedPrice"].Value = selected.OidUntaxedPrice;
                row.Cells["colOriginalTaxedPrice"].Value = selected.OidIncludingTax;

                int.TryParse(texttax_Rate?.Text, out var taxRate);
                row.Cells["colTaxRate"].Value = taxRate.ToString();

                // 设置原价格作为默认值，新价格将通过API获取
                var baseUntaxed = selected.OidUntaxedPrice ?? 0m;
                var baseTaxed = selected.OidIncludingTax ?? 0m;
                row.Cells["colUntaxedPrice"].Value = baseUntaxed > 0 ? baseUntaxed.ToString("F2") : string.Empty;
                row.Cells["colTaxedPrice"].Value = baseTaxed > 0 ? baseTaxed.ToString("F2") : string.Empty;
                row.Tag = selected;

                // 添加物料后，重新加载新价格数据并反填
                _ = LoadNewPricesAndFillBack();
            });
            dialog.ShowDialog(this);
        }

        private async void btnedit_Click(object sender, EventArgs e)
        {
            try
            {
                // 校验基础信息
                if (dgvmater == null || dgvmater.Rows.Count == 0)
                {
                    MessageBox.Show("请先添加物料", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (string.IsNullOrWhiteSpace(textpricingNode?.Text))
                {
                    MessageBox.Show("核价编号不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!DateTime.TryParse(datepricing_Date?.text, out var pricingDate))
                {
                    MessageBox.Show("请填写有效的核价日期", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (cbosupplierId?.SelectedValue == null)
                {
                    MessageBox.Show("请选择供应商", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!int.TryParse(texttax_Rate?.Text, out var taxRate) || taxRate < 0)
                {
                    MessageBox.Show("请填写有效的税率", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 组装明细
                var items = new List<CreateProcurement_PricingDtos>();
                foreach (DataGridViewRow row in dgvmater.Rows)
                {
                    if (!(row.Tag is Material_TableDtos material)) continue;

                    if (!decimal.TryParse(row.Cells["colUntaxedPrice"].Value?.ToString(), out var untaxed))
                    {
                        MessageBox.Show("请填写有效的新未税价格", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    decimal taxed;
                    if (!decimal.TryParse(row.Cells["colTaxedPrice"].Value?.ToString(), out taxed))
                    {
                        taxed = taxRate > 0 ? Math.Round(untaxed * (1 + taxRate / 100.0m), 2) : untaxed;
                    }

                    items.Add(new CreateProcurement_PricingDtos
                    {
                        PricingNode = _pricingNode,
                        PricingName = textpricingName?.Text?.Trim(),
                        Pricing_Date = pricingDate,
                        SupplierId = int.Parse(cbosupplierId.SelectedValue.ToString()),
                        Tax_Rate = taxRate,
                        Notes = textnotes?.Text?.Trim(),
                        Material_Id = material.Id,
                        Untaxed_Price = untaxed,
                        Taxed_Price = taxed,
                        State = "待审核"
                    });
                }

                if (items.Count == 0)
                {
                    MessageBox.Show("没有可提交的物料明细", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 组装与后端更一致的请求体：包含头信息 + 明细
                var requestData = new
                {
                    pricingNode = _pricingNode,
                    pricingName = textpricingName?.Text?.Trim(),
                    pricing_Date = pricingDate,
                    supplierId = int.Parse(cbosupplierId.SelectedValue.ToString()),
                    tax_Rate = taxRate,
                    notes = textnotes?.Text?.Trim(),
                    items
                };
                // 调试日志
                Console.WriteLine($"准备发送的数据: {JsonConvert.SerializeObject(requestData, Formatting.Indented)}");
                Console.WriteLine($"明细数量: {items.Count}");

                // 尝试在URL中附带pricingNode，兼容部分后端路由风格
                var endpoint = $"api/Write/UpdateProcurement_Pricing?pricingNode={Uri.EscapeDataString(_pricingNode ?? string.Empty)}";
                var response = await _apiClient.PutAsync<object, TestApiResult<string>>(endpoint, requestData);

                if (response != null && response.code == 200)
                {
                    MessageBox.Show(response.msg ?? "采购核价更新成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    // 调用刷新回调
                    _refreshCallback?.Invoke();

                    this.Close();
                }
                else
                {
                    MessageBox.Show($"更新失败：{response?.msg ?? "接口调用失败"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存时出现异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 手动触发新价格反填（用于测试）
        /// </summary>
        public async void ManualTriggerNewPriceFill()
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                await LoadNewPricesAndFillBack();
                MessageBox.Show("新价格反填完成，请查看控制台日志", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"手动触发新价格反填失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
    }
}
